//
//  XDBindBankCardViewController.m
//  xindailianmeng
//
//  Created by 张东 on 2017/2/25.
//  Copyright © 2017年 xindailianmeng.cn. All rights reserved.
//

#import "XDBindBankCardViewController.h"
#import "AFHTTPSessionManager+POST.h"
#import "ZHRTRequestFailureShowViewOrDetail.h"
#import "XDBankInfoViewController.h"
#import "SDWebImageManager.h"
#import "XDMybankCardViewController.h"
#import "XDToRechargeViewController.h"
@interface XDBindBankCardViewController ()<UITextFieldDelegate>

@property (nonatomic, weak) UITextField *bankCardTf;

@property (nonatomic, weak) UIButton *nextBtn;

@property (nonatomic, weak) UILabel  *cardNoLb;

@property (nonatomic, weak) UILabel  *nameLb;

@property (nonatomic, weak) UIButton  *depositBankBtn;

@property (nonatomic, copy) NSString *bankCode;
@end

@implementation XDBindBankCardViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"绑定银行卡";
    [self setUI];
    [self loadData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bankNameChange:) name:@"XDBankInfoCellNoti" object:nil];
    
    
}

- (void)bankNameChange:(NSNotification *)noti {
    
    NSDictionary *info = noti.userInfo;
    
    [[SDWebImageManager sharedManager] downloadImageWithURL:info[@"bankIconUrl"] options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
        
        
        [self.depositBankBtn setImage:[self OriginImage:image scaleToSize:CGSizeMake(20.0, 20.0)] forState:UIControlStateNormal];
        [self.depositBankBtn setTitle:info[@"bankName"] forState:UIControlStateNormal];
        [self.depositBankBtn setTitleColor:kColorRGB(51, 51, 51) forState:UIControlStateNormal];
        
        self.bankCode = info[@"bankCode"];
    }];
}

-(UIImage*)OriginImage:(UIImage *)image scaleToSize:(CGSize)size{
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    //Determine whether the screen is retina
    if([[UIScreen mainScreen] scale] == 2.0){
        
        UIGraphicsBeginImageContextWithOptions(size, NO, 2.0);
    }else{
        UIGraphicsBeginImageContext(size);
    }
    // 绘制改变大小的图片
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();        // 使当前的context出堆栈
    UIGraphicsEndImageContext();        // 返回新的改变大小后的图片
    return scaledImage;
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:@"XDBankInfoCellNoti"];
}

- (void)loadData {
    
        NSDictionary * param = @{@"method":@"isVerifiedAndSafe"};
        [AFHTTPSessionManager POSTWithParams:param success:^(NSURLSessionDataTask *task, id responseObject) {
            if ([responseObject[@"code"] isEqualToString:@"100000"]) {
                
                self.cardNoLb.text = responseObject[@"result"][@"idNumber"];
                self.nameLb.text = responseObject[@"result"][@"realName"];
            } else if ([responseObject[@"code"] isEqualToString:@"100001"]){ // 超时
                
                
            } else {
                
                [ZHRTRequestFailureShowViewOrDetail showViewDetail:responseObject[@"message"] view:self.view];
            }
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            
        }];

}


- (void)setUI {
    
    UIView *view = [[UIView alloc] initWithFrame:kScreenB];
    view.backgroundColor = kColorRGB(234, 234, 234);
    [self.view addSubview: view];
    
    UIView *tipBackground = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 30)];
    tipBackground.backgroundColor = kColorRGB(232,213,177);
    [view addSubview:tipBackground];
    
    UILabel *tipLb = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, kScreenW, 30)];
    tipLb.text = @"* 持卡人信息必须与实名认证相符";
    tipLb.textColor = kColorRGB(24,24,24);
    tipLb.font = kBaseFont_(12);
    
    [tipBackground addSubview:tipLb];
    
    
    UITextField *infoTf =  [self createTextFieldWithFrame:CGRectMake(0, CGRectGetMaxY(tipLb.frame) + 10, kScreenW, 75) textFont:kBaseFont_(16) textColor:kColorRGB(51, 51, 51) placeholder:@"" placeholderFont:kBaseFont_(13) leftTitle:@"认证信息" delegate:self inView:view tag:1000];
    infoTf.enabled = NO;
    
    UILabel *cardNoLb = [[UILabel alloc] initWithFrame:CGRectMake(0, 18, kScreenW - 15, 18)];
    cardNoLb.textColor = kColorRGB(51, 51, 51);
    cardNoLb.font = kBaseFont_(16);
    cardNoLb.text = @" ";
    cardNoLb.textAlignment = NSTextAlignmentRight;
    self.cardNoLb = cardNoLb;
    [infoTf addSubview:cardNoLb];
    UILabel *nameLb = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(cardNoLb.frame) + 2, kScreenW - 15, 18)];
    nameLb.textColor = kColorRGB(51, 51, 51);
    nameLb.font = kFont_(16);
    nameLb.text = @" ";
    nameLb.textAlignment = NSTextAlignmentRight;
    self.nameLb = nameLb;
    [infoTf addSubview:nameLb];
    
    
    
    
    UIButton *bankName = [[UIButton alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(infoTf.frame) + 10, kScreenW, 50)];
    [bankName setBackgroundImage:[UIImage imageNamed:@"textfield-1"] forState:UIControlStateNormal];
    [bankName setBackgroundImage:[UIImage imageNamed:@"textfield-1"] forState:UIControlStateHighlighted];
    [bankName setTitle:@"银行名称" forState:UIControlStateNormal];
    [bankName setImage:[UIImage imageNamed:@"nextInd"] forState:UIControlStateNormal];
    [bankName setTitleColor:kColorRGB(102,102,102) forState:UIControlStateNormal];
    bankName.titleLabel.font = kBaseFont_(14);
    bankName.contentEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 15);
    bankName.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    bankName.imageEdgeInsets = UIEdgeInsetsMake(0, kScreenW - 30 - 6, 0, 0);
    bankName.titleEdgeInsets = UIEdgeInsetsMake(0,-6, 0, 0);
    [bankName addTarget:self action:@selector(selectBankName) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:bankName];
    
    UIButton *depositBankBtn =
    [[UIButton alloc] initWithFrame:CGRectMake(0, 0, kScreenW - 30, 50)];
    
    [depositBankBtn setTitle:@"选择开户行" forState:UIControlStateNormal];
    [depositBankBtn setTitleColor:kColorRGB(153,153,153) forState:UIControlStateNormal];
    depositBankBtn.titleLabel.font = kBaseFont_(13);
    depositBankBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    depositBankBtn.userInteractionEnabled = NO;
    self.depositBankBtn = depositBankBtn;
    [bankName addSubview:depositBankBtn];

 
    
    UIButton *tipBtn = [[UIButton alloc] initWithFrame:CGRectMake(150, CGRectGetMaxY(bankName.frame), kScreenW - 150 - 15, 38)];
    [tipBtn setTitle:@"查看支持银行卡及限额" forState:UIControlStateNormal];
    [tipBtn setTitleColor:kColorRGB(187,147,115) forState:UIControlStateNormal];
    tipBtn.titleLabel.font = kBaseFont_(13);
    tipBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [tipBtn addTarget:self action:@selector(tipBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:tipBtn];
    
    
    
    UITextField *bankCardTf = [self createTextFieldWithFrame:CGRectMake(0, CGRectGetMaxY(bankName.frame) + 38, kScreenW, 50) textFont:kBaseFont_(16) textColor:kColorRGB(51, 51, 51) placeholder:@"请输入银行卡号" placeholderFont:kBaseFont_(13) leftTitle:@"银行卡号" delegate:self inView:view tag:1002];
    bankCardTf.rightView = [[UIButton alloc] initWithFrame:CGRectMake(0, 1, 15, 48)];
    bankCardTf.rightViewMode = UITextFieldViewModeAlways;
     self.bankCardTf = bankCardTf;
    UIImage *img = [UIImage imageNamed:@"sure_hieght"];
    UIButton *nextBtn = [[UIButton alloc] initWithFrame:CGRectMake((kScreenW - img.size.width) * 0.5 ,CGRectGetMaxY(bankCardTf.frame) + 38 , img.size.width, img.size.height)];
    [nextBtn setBackgroundImage:img forState:UIControlStateNormal];
    [nextBtn setBackgroundImage:[UIImage imageNamed:@"sure_nor"] forState:UIControlStateDisabled];
    nextBtn.enabled = NO;
    [nextBtn addTarget:self action:@selector(nextBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:nextBtn];
    self.nextBtn = nextBtn;
}

//修改UITextField的placeholder字体并垂直居中
- (NSAttributedString *)textFieldAttributedPlaceholderWith:(UITextField *)textField placeholder:(NSString *)placeholder placeholderFont:(UIFont *)placeholderFont  {
    NSMutableParagraphStyle *style = [textField.defaultTextAttributes[NSParagraphStyleAttributeName] mutableCopy];
    style.minimumLineHeight = textField.font.lineHeight - (textField.font.lineHeight - placeholderFont.lineHeight) / 2.0;
    NSAttributedString *attr = [[NSAttributedString alloc] initWithString:placeholder attributes:@{NSFontAttributeName:placeholderFont, NSParagraphStyleAttributeName : style}];
    return attr;
}

- (UITextField *)createTextFieldWithFrame:(CGRect)frame textFont:(UIFont *)textFont textColor:(UIColor *)textColor placeholder:(NSString *)placeholder placeholderFont:(UIFont *)placeholderFont leftTitle:(NSString *)leftTitle delegate:(id)obj inView:(UIView *)inView tag:(NSInteger)tag {
    
    UITextField *textField = [[UITextField alloc] initWithFrame:frame];
    textField.background = [UIImage imageNamed:@"textfield-1"];
    textField.textAlignment = NSTextAlignmentRight;
    textField.textColor =  textColor;
    textField.font = textFont;
    textField.attributedPlaceholder = [self textFieldAttributedPlaceholderWith:textField placeholder:placeholder placeholderFont:placeholderFont];
    textField.keyboardType = UIKeyboardTypeNumberPad;
    textField.tag = tag;
    textField.delegate = self;

    
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 1, 80, 48)];
    leftView.backgroundColor = [UIColor whiteColor];
    
    UILabel *nameLb = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 80, 48)];
    nameLb.text = leftTitle;
    nameLb.textColor = kColorRGB(102,102,102);
    nameLb.font = kBaseFont_(14);
    nameLb.textAlignment = NSTextAlignmentLeft;
    [leftView addSubview:nameLb];
    textField.leftView = leftView;
    textField.leftViewMode = UITextFieldViewModeAlways;
    [inView addSubview:textField];
    return textField;
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

    [self.bankCardTf resignFirstResponder];
  
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    
    
    
    NSLog(@"%@",textField.text);
    if (textField.tag == 1002) {
        
       
         NSString *bankNumber = [[textField.text stringByReplacingOccurrencesOfString:@" " withString:@""]stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        NSString *textFieldText = [bankNumber stringByAppendingString:string];
        if (textFieldText.length > 5 || string.length > 2) {
            NSDictionary * param = @{@"method":@"findInfoByBanlBin",@"bankNumber":textFieldText};
            [AFHTTPSessionManager POSTWithParams:param success:^(NSURLSessionDataTask *task, id responseObject) {
                if ([responseObject[@"code"] isEqualToString:@"100000"]) {
                    
                    
                    NSDictionary *dic = responseObject[@"result"][@"bankValidate"];
                    [[SDWebImageManager sharedManager] downloadImageWithURL:dic[@"bankIconUrl"] options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
                        
                        
                        [self.depositBankBtn setImage:[self OriginImage:image scaleToSize:CGSizeMake(20.0, 20.0)] forState:UIControlStateNormal];
                        [self.depositBankBtn setTitle:dic[@"bankName"] forState:UIControlStateNormal];
                        [self.depositBankBtn setTitleColor:kColorRGB(51, 51, 51) forState:UIControlStateNormal];
        
                        self.bankCode = dic[@"bankCode"];
                        
                        if (textFieldText.length > 14 && self.bankCode) {
                            
                            self.nextBtn.enabled = YES;
                            
                        } else {
                            
                            
                            self.nextBtn.enabled = NO;
                            
                            
                        }
                        
                    }];
                    
                } else if ([responseObject[@"code"] isEqualToString:@"100001"]){ // 超时
                    
                    
                } else {
                    
//                    [ZHRTRequestFailureShowViewOrDetail showViewDetail:responseObject[@"message"] view:self.view];
                }
            } failure:^(NSURLSessionDataTask *task, NSError *error) {
                
            }];
            
        }
        
      
        // 4位分隔银行卡卡号
        NSString *text = [textField text];
        
        NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789\b"];
        string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
        if ([string rangeOfCharacterFromSet:[characterSet invertedSet]].location != NSNotFound) {
            return NO;
        }
        
        text = [text stringByReplacingCharactersInRange:range withString:string];
        text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
        
        NSString *newString = @"";
        while (text.length > 0) {
            NSString *subString = [text substringToIndex:MIN(text.length, 4)];
            newString = [newString stringByAppendingString:subString];
            if (subString.length == 4) {
                newString = [newString stringByAppendingString:@" "];
            }
            text = [text substringFromIndex:MIN(text.length, 4)];
        }
        
        newString = [newString stringByTrimmingCharactersInSet:[characterSet invertedSet]];
        
        if ([newString stringByReplacingOccurrencesOfString:@" " withString:@""].length >= 21) {
            return NO;
        }
        
        [textField setText:newString];
        
        return NO;
    }
    return YES;
}
- (void)selectBankName {
    
    
    NSLog(@"选择银行");
    XDBankInfoViewController *bankInfo = [[XDBankInfoViewController alloc] init];
    
    [self.navigationController pushViewController:bankInfo animated:YES];
    
}

- (void)nextBtnClick:(UIButton *)nextBtn {
    
    NSString *bankNumber = [[self.bankCardTf.text stringByReplacingOccurrencesOfString:@" " withString:@""]stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    NSString *bankName = [[self.depositBankBtn.titleLabel.text stringByReplacingOccurrencesOfString:@" " withString:@""]stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSDictionary * param = @{@"method":@"bindBankCard",@"bankNumber":bankNumber,@"bankCode":self.bankCode,@"bindType":@"1",@"bankName":bankName};
    [AFHTTPSessionManager POSTWithParams:param success:^(NSURLSessionDataTask *task, id responseObject) {
        
        
        if ([responseObject[@"code"] isEqualToString:@"100000"]) {
//            6217 0000 1008 4626 509
      // [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
                for (UIViewController *vc in self.navigationController.viewControllers) {
                    
                    
                    if ([vc isKindOfClass:[XDToRechargeViewController class]] ) {
                        [self.navigationController popToViewController:vc animated:YES];
                    }
                }
        } else if ([responseObject[@"code"] isEqualToString:@"100001"]){ // 超时
            
            
        } else {
            
            [ZHRTRequestFailureShowViewOrDetail showViewDetail:responseObject[@"message"] view:self.view];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];

}

- (void)tipBtnClick {
    
    NSLog(@"查看支持银行卡及限额");
    XDBankInfoViewController *bankInfo = [[XDBankInfoViewController alloc] init];
    
    [self.navigationController pushViewController:bankInfo animated:YES];
    
}

- (BOOL) IsBankCard:(NSString *)cardNumber
{
    if(cardNumber.length==0)
    {
        return NO;
    }
    NSString *digitsOnly = @"";
    char c;
    for (int i = 0; i < cardNumber.length; i++)
    {
        c = [cardNumber characterAtIndex:i];
        if (isdigit(c))
        {
            digitsOnly =[digitsOnly stringByAppendingFormat:@"%c",c];
        }
    }
    int sum = 0;
    int digit = 0;
    int addend = 0;
    BOOL timesTwo = false;
    for (NSInteger i = digitsOnly.length - 1; i >= 0; i--)
    {
        digit = [digitsOnly characterAtIndex:i] - '0';
        if (timesTwo)
        {
            addend = digit * 2;
            if (addend > 9) {
                addend -= 9;
            }
        }
        else {
            addend = digit;
        }
        sum += addend;
        timesTwo = !timesTwo;
    }
    int modulus = sum % 10;
    return modulus == 0;
}

@end
